package fr.oz.view.bg 
{
	import caurina.transitions.Tweener;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import fr.digitas.flowearth.conf.Conf;
	/**
	 * ...
	 * @author Fazermokeur
	 */
	public class BackgroundManager extends Sprite
	{
		private var loader:Loader;
		private var fond:Bitmap;
		private var previousFond:Bitmap;
		
		public function BackgroundManager() 
		{
			addEventListener(Event.ADDED_TO_STAGE, init);
			
			loadView();
		}
		
		private function loadView():void
		{
			var url:String;
			var date:Date = new Date();
			date.getDate();
			var hour:Number = date.getHours();
			trace("il est " + hour+"h");
			if (hour > 19 || hour < 8) {
				trace("Il fait nuit!");
				url = Conf.getDatas("common").background.night;
			}else {
				trace("Il fait jour!");
				url = Conf.getDatas("common").background.day;
			}
			
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleBGComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, bgError);
			
			loader.load(new URLRequest(url), new LoaderContext(false, ApplicationDomain.currentDomain));
		}
		
		private function handleBGComplete(e:Event):void 
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, handleBGComplete);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, bgError);
			
			if (fond != null)
			{
				previousFond = fond;
			}
			
			var bmpd:BitmapData = new BitmapData(loader.content.width, loader.content.height);
			bmpd.draw(loader.content);
			fond = new Bitmap();
			fond.bitmapData = bmpd;
			addChild(fond);
			fond.alpha = 0;
			Tweener.addTween(fond, { alpha:1, time:1, onComplete:disposePrevious } );
			
			loader = null;
		}
		
		private function disposePrevious():void
		{
			if(previousFond != null){
				removeChild(previousFond);
				previousFond.bitmapData.dispose();
				previousFond = null;
			}
		}
		
		private function bgError(e:IOErrorEvent):void 
		{
			
		}
		
		private function init(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
		}
		
		
		
	}

}